package urna;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.rmi.*;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import javax.swing.JButton;
import javax.swing.JFrame;

public class LectordeTarjetas extends UnicastRemoteObject implements InterfaceLectordeTarjetas, MouseListener {
	
	private static final long serialVersionUID = 8166067461028875505L;
	
	private Registry registry;
	public JFrame visual;
	private int port;
	
	public void startRegistry() throws RemoteException {
		registry = java.rmi.registry.LocateRegistry.createRegistry(port);
	}
	
	public void registerObject(String name, Remote remoteObj) throws RemoteException, AlreadyBoundException {
		registry.bind(name, remoteObj);
	}
	
	public boolean ping() {
		return true;
	}
	
	private void enviarTarjeta() {
		//Levantar archivo que dejo la maquina
		BufferedReader archivo;		
		//Buscar un GestordeDatos
		InterfaceGestordeDatos gestor;
		try {
			archivo = new BufferedReader(new FileReader("tarjeta.txt"));
			gestor = (InterfaceGestordeDatos) registry.lookup("GestordeDatos");
			
			//Enviarle el archivo
			String linea;
			while ((linea = archivo.readLine()) != null) {
				gestor.registrar(linea);
			}
			
		} catch (Exception e) {
		}
		
	}
	
	public LectordeTarjetas(int port) throws RemoteException {
		this.port = port;
		visual = new JFrame();
		visual.setBounds(800, 50, 200, 200);
		visual.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JButton jb = new JButton("Ingresar tarjeta");
		visual.add(jb);
		jb.addMouseListener(this);
		visual.setVisible(true);
        try 
        {
        	startRegistry();
			registerObject("LectordeTarjetas", this);
		}
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }

	}
	
    public static void main(String[] args) {
        try {
        	if (args.length > 0) {
        		new LectordeTarjetas(Integer.parseInt(args[0]));
        		System.out.println("El lector de tarjetas se encuentra funcionando. (port = "+args[0]+")");
        	}
        	else System.out.println("Faltan parametros para la inicializacion del Lector. Parametro1=puerto (1000)");
		} catch (RemoteException e) {
			System.out.println(e.getMessage());
		}
        
    }

	public void mouseClicked(MouseEvent arg0) {
		enviarTarjeta();
		
	}

	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
    
}
